package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.dto.UserInfo;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.service.MenuService;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("sys_user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MenuService menuService;
    //分页查询
    @GetMapping("list")
    public ResultData list(String login_name,String phone,String status,Long page, Long limit){
        log.info("login_name={},phone={},status={},page={},limit={}",login_name,phone,status,page,limit);
        //定义页面构造器
        Page<User> userPage=new Page<>(page,limit);
        Page<SysUserInfo> userInfoPage=new Page<>();
        //定义条件构造器
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        //判断是否注入条件
        if (!("".equals(login_name))){
            lqw.like(User::getLogin_name,login_name);
        }
        if (!("".equals(phone))){
            lqw.like(User::getPhone,phone);
        }
        if (!("".equals(status))){
            lqw.like(User::getStatus,status);
        }

        /*lqw.eq(login_name != null,User::getLogin_name,login_name);
        lqw.eq(phone !=null ,User::getPhone,phone);
        lqw.eq(status !=null ,User::getStatus,status);*/
        //查询页面信息
        userService.page(userPage,lqw);
        //复制页面
        BeanUtils.copyProperties(userPage,userInfoPage,"records");
        //添加职位id和职位名称
        List<User> records = userPage.getRecords();
        List<SysUserInfo> collect1 = records.stream().map((item) -> {
            //返回对象类型
            SysUserInfo sysUserInfo = new SysUserInfo();
            //复制信息
            BeanUtils.copyProperties(item, sysUserInfo);
            LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //获取职位id，把test类型转化为string，去掉[]和""
            String strip = StringUtils.strip(item.getRole_id(), "[]");
            String[] split = strip.split(",");
            for (int i = 0; i < split.length; i++) {
                split[i]=StringUtils.replace(split[i], "\"", "");
            }
            System.out.println(split);
            roleLambdaQueryWrapper.in(Role::getId,split);
            List<Role> list = roleService.list(roleLambdaQueryWrapper);
            //获取查询出来的职位id
            List<String> collect2 = list.stream().map((item2 -> {
                return item2.getId();
            })).collect(Collectors.toList());
            //获取查询出来的职位名称
            List<String> collect = list.stream().map((item1) -> {
                return item1.getName();
            }).collect(Collectors.toList());
            //赋值
            sysUserInfo.setRole_id(collect2);
            sysUserInfo.setRolename(collect);
            return sysUserInfo;
        }).collect(Collectors.toList());
        //赋值records
        userInfoPage.setRecords(collect1);
        //返回查询信息
        return ResultData.ok("查询成功",PageResult.init(userInfoPage.getTotal(),page,limit,userInfoPage.getRecords()));

    }
    //删除用户
    @GetMapping("del")
    public ResultData delete(String id){
        log.info("id:{}",id);
        //判断用户状态和权限
        User user1 = userService.getById(id);
        //是否为系统默认数据
        if (("1".equals(user1.getDefault_data()))){
            return ResultData.error("系统默认数据，无法删除");
        }
        //状态是否为启动
        if (user1.getStatus()==1){
            return ResultData.error("用户状态为启用,无法删除");
        }
       /* LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取登录人员信息，把test类型转化为string，去掉[]和""
        String userId = UserHolder.getUserId();
        User user2 = userService.getById(userId);
        String strip = StringUtils.strip(user2.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            split[i]=StringUtils.replace(split[i], "\"", "");
        }
        //String replace = StringUtils.replace(strip, "\"", "");
        //String[] split = replace.split(",");
        //注入条件
        roleLambdaQueryWrapper.in(Role::getId,split);
        List<Role> list1 = roleService.list(roleLambdaQueryWrapper);
        //获取id
        List<String> collect = list1.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        //根据权限id去查询是否有用户管理权限
        LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.in(RoleMenu::getRoleId,collect);
        List<RoleMenu> list = roleMenuService.list(roleMenuLambdaQueryWrapper);
        for (RoleMenu roleMenu : list) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("系统设置".equals(menu.getTitle())){
                LambdaQueryWrapper<Menu> menuLambdaQueryWrapper1=new LambdaQueryWrapper<>();
                menuLambdaQueryWrapper1.eq(Menu::getPid,menuId);
                List<Menu> list3 = menuService.list(menuLambdaQueryWrapper1);
                for (Menu Menu2 : list3) {
                    //二级权限
                    if ("用户管理".equals(Menu2.getTitle())) {
                        LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        menuLambdaQueryWrapper.eq(Menu::getPid, Menu2.getId());
                        List<Menu> list2 = menuService.list(menuLambdaQueryWrapper);
                        for (Menu Menu1 : list2) {
                            //Menu menu1 = menuService.getById(Menu1.getId());
                            //三级权限
                            if ("删除".equals(Menu1.getTitle())) {
                                //根据用户id删除用户数据

                            }
                        }
                    }
                }
            }
        }*/
        if (roleService.RoleUtils("系统设置","用户管理","删除")){
            userService.removeById(id);
            return ResultData.ok("删除成功","删除成功");
        }
        //否则没有权限删除
        return ResultData.error("删除失败，该用户没有权限");
    }
    //添加功能
    @PostMapping("add")
    public ResultData add(@RequestBody HashMap<String,Object> map){
       // System.out.println(map);
        //封装对象
        User user=new User();
        String login_name = (String) map.get("login_name");
        user.setLogin_name(login_name);
        String password = (String) map.get("password");
        password= DigestUtils.md5Hex(password);
        user.setPassword(password);
        String phone = (String) map.get("phone");
        user.setPhone(phone);
        String name = (String) map.get("name");
        user.setName(name);
        String email = (String) map.get("email");
        user.setEmail(email);
        Integer status = (Integer) map.get("status");
        user.setStatus(status);
        ArrayList<String> role_id = (ArrayList<String>) map.get("role_id");
        String role_menus = "[";
        for (int i = 0; i < role_id.size(); i++) {
             if(i <role_id.size()-1){
                role_menus += "\""+role_id.get(i)+"\""+",";
            }else {
                role_menus += "\""+role_id.get(i)+"\""+"]";
            }

        }
        user.setRole_id(role_menus);
        user.setCreate_date(LocalDateTime.now());
        /*LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取登录人员信息，把test类型转化为string，去掉[]和""
        String userId = UserHolder.getUserId();
        User user2 = userService.getById(userId);
        String strip = StringUtils.strip(user2.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            split[i]=StringUtils.replace(split[i], "\"", "");
        }
        //String replace = StringUtils.replace(strip, "\"", "");
        //String[] split = replace.split(",");
        roleLambdaQueryWrapper.in(Role::getId,split);
        List<Role> list1 = roleService.list(roleLambdaQueryWrapper);
        //获取id
        List<String> collect = list1.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        //System.out.println(collect);
        //根据权限id去查询是否有用户管理权限
        LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.in(RoleMenu::getRoleId,collect);
        //roleMenuLambdaQueryWrapper.in(RoleMenu::getRoleId,collect);
        List<RoleMenu> list = roleMenuService.list(roleMenuLambdaQueryWrapper);
        for (RoleMenu roleMenu : list) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("系统设置".equals(menu.getTitle())) {
                LambdaQueryWrapper<Menu> menuLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                menuLambdaQueryWrapper1.eq(Menu::getPid, menuId);
                List<Menu> list3 = menuService.list(menuLambdaQueryWrapper1);
                for (Menu Menu2 : list3) {
                    //二级权限
                    if ("用户管理".equals(Menu2.getTitle())) {
                        LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        menuLambdaQueryWrapper.eq(Menu::getPid, Menu2.getId());
                        List<Menu> list2 = menuService.list(menuLambdaQueryWrapper);
                        for (Menu Menu1 : list2) {
                            //Menu menu1 = menuService.getById(Menu1.getId());
                            //三级权限
                            if ("增加".equals(Menu1.getTitle())) {//添加数据
                                userService.save(user);
                                return ResultData.ok("添加成功", "添加成功");
                            }
                        }
                    }
                }
            }
        }*/
        if (roleService.RoleUtils("系统设置","用户管理","增加")){
            userService.save(user);
            return ResultData.ok("添加成功", "添加成功");
        }
        //否则没有权限添加
        return ResultData.error("添加失败,无权限添加!");
    }
    /*查询单个*/
    @GetMapping("rowInfo")
    public ResultData getById(String id){
        log.info("查询的id为{}",id);
        UserInfo userDto=new UserInfo();
        User user = userService.getById(id);
        user.setPassword("******");
        String role_id = user.getRole_id();
        List<String> list=new ArrayList<>();
        String strip = StringUtils.strip(role_id, "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            split[i]=StringUtils.replace(split[i], "\"", "");
            list.add(split[i]);
        }
        BeanUtils.copyProperties(user,userDto,"role_id");
        userDto.setRole_id(list);
        return ResultData.ok("查询成功",userDto);
    }
    //修改功能
    @PostMapping("update")
    public ResultData update(@RequestBody HashMap<String,Object> map){
        String id = (String) map.get("id");
        User user = userService.getById(id);
        if (map.get("login_name")!=null) {
            String login_name = (String) map.get("login_name");
            user.setLogin_name(login_name);
        }
        if (map.get("password")!=null) {
            String password = (String) map.get("password");
             password  = DigestUtils.md5Hex(password);
            user.setPassword(password);
        }
        if (map.get("phone")!=null) {
            String phone = (String) map.get("phone");
            user.setPhone(phone);
        }
        if (map.get("name")!=null) {
            String name = (String) map.get("name");
            user.setName(name);
        }
        if (map.get("email")!=null) {
            String email = (String) map.get("email");
            user.setEmail(email);
        }
        Integer status = (Integer) map.get("status");
        user.setStatus(status);
        ArrayList<String> role_id = (ArrayList<String>) map.get("role_id");
        if (role_id!=null) {
            String role_menus = "[";
            for (int i = 0; i < role_id.size(); i++) {
                if (i < role_id.size() - 1) {
                    role_menus += "\"" + role_id.get(i) + "\"" + ",";
                } else {
                    role_menus += "\"" + role_id.get(i) + "\"" + "]";
                }
            }
            user.setRole_id(role_menus);
        }
        user.setUpdate_date(LocalDateTime.now());

        if (roleService.RoleUtils("系统设置","用户管理","更新")){
            userService.updateById(user);
            return ResultData.ok("更新成功", "更新成功");
        }

        //否则没有权限添加
        return ResultData.error("更新失败,无权限更新!");
    }
}
 /* LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取登录人员信息，把test类型转化为string，去掉[]和""
        String userId = UserHolder.getUserId();
        User user2 = userService.getById(userId);
        String strip = StringUtils.strip(user2.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            split[i]=StringUtils.replace(split[i], "\"", "");
        }
        //String replace = StringUtils.replace(strip, "\"", "");
        //String[] split = replace.split(",");
        roleLambdaQueryWrapper.in(Role::getId,split);
        List<Role> list1 = roleService.list(roleLambdaQueryWrapper);
        List<String> collect = list1.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        //System.out.println(collect);
        //根据权限id去查询是否有用户管理权限
        LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.in(RoleMenu::getRoleId,collect);
        //roleMenuLambdaQueryWrapper.in(RoleMenu::getRoleId,collect);
        List<RoleMenu> list = roleMenuService.list(roleMenuLambdaQueryWrapper);
        for (RoleMenu roleMenu : list) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("系统设置".equals(menu.getTitle())) {
                LambdaQueryWrapper<Menu> menuLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                menuLambdaQueryWrapper1.eq(Menu::getPid, menuId);
                List<Menu> list3 = menuService.list(menuLambdaQueryWrapper1);
                for (Menu Menu2 : list3) {
                    //二级权限
                    if ("用户管理".equals(Menu2.getTitle())) {
                        LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        menuLambdaQueryWrapper.eq(Menu::getPid, Menu2.getId());
                        List<Menu> list2 = menuService.list(menuLambdaQueryWrapper);
                        for (Menu Menu1 : list2) {
                            //Menu menu1 = menuService.getById(Menu1.getId());
                            //三级权限
                            if ("更新".equals(Menu1.getTitle())) {
                                //添加数据
                                userService.updateById(user);
                                return ResultData.ok("更新成功", "更新成功");
                            }
                        }
                    }
                }
            }
        }*/